package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	read()
}

func read() {
	scanner := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("请输入被占用的端口, 输入(0/enter) 退出: ")
		scanner.Scan()
		port, _ := strconv.Atoi(scanner.Text())
		if port == 0 {
			os.Exit(0)
		}
		portInUse(port)
	}
}

func portInUse(portNumber int) {
	pid := 0
	var outBytes bytes.Buffer
	cmd := exec.Command("cmd", "/c", "netstat", "-ano", "-p", "tcp", "|", "findstr", strconv.Itoa(portNumber))
	cmd.Stdout = &outBytes
	cmd.Run()
	resStr := outBytes.String()
	r := regexp.MustCompile(`\s\d+\s`).FindAllString(resStr, -1)
	if len(r) > 0 {
		pid, _ = strconv.Atoi(strings.TrimSpace(r[0]))
		kill(pid)
		return
	}
	fmt.Println("端口号未被占用")
	return
}

func kill(port int) {
	var res bytes.Buffer
	cmd := exec.Command("taskkill", "/pid", strconv.Itoa(port), "-t", "-f")
	cmd.Stdout = &res
	cmd.Run()
	fmt.Println("进程已被结束")
}
